package com.sun.showcase.conf.security;

import com.sun.showcase.biz.basic.service.TenantService;
import com.sun.showcase.biz.config.tenant.BaseContextHandler;
import com.sun.showcase.biz.config.tenant.TenantProperties;
import com.sun.showcase.client.domain.basic.Tenant;
import com.sun.showcase.exception.DefaultException;
import com.sun.showcase.utils.SpringApplicationContextHolder;
import com.sun.showcase.utils.StringConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class TenantCodeFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        TenantProperties tenantProperties = (TenantProperties)SpringApplicationContextHolder.getBean("tenantProperties");
        if(!tenantProperties.isEnable()){
            chain.doFilter(request, response);
            return;
        }
        // 获取域名 aaa.showcase.com, 那么aaa则为tenantCode
        String host = request.getServerName();//-->localhost
        if(!StringConstant.LOCAL_DOMAIN.equals(host) && host.indexOf(StringConstant.SPOT)>=0){
            String code = host.split("\\.")[0];
            code = StringConstant.MAIN_DOMAIN.equalsIgnoreCase(code)?StringConstant.EMPTY:code;
            if(StringUtils.isNotEmpty(code)){
                TenantService tenantService = (TenantService)SpringApplicationContextHolder.getBean("tenantService");
                Tenant tenant = tenantService.getByTenantCode(code);
                if(tenant != null){
                    BaseContextHandler.setTenant(code);
                }else {
                    throw new DefaultException("无效租户");
                }
            }
        }

        // 继续调用 Filter 链
        chain.doFilter(request, response);
        BaseContextHandler.remove();
    }

}
